import axios from "axios";
import { jsonToQueryString } from "./common";
import { message } from 'ant-design-vue'
import type { RequestParams } from "@/utils/ts_interface";
import { useSpinningStore } from "@/stores/useSpinning";
import { useUserStore } from '@/stores/useUser'
import { storeToRefs } from "pinia";
const { access_token } = storeToRefs(useUserStore())
const { changeSpinning } = useSpinningStore()

const instance = axios.create({
    timeout: 15000,
    headers: { "Content-Type": "application/json; charset=utf-8" },
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    if (access_token) {
        config.headers["Authorization"] = `Bearer ${access_token.value}`
    } else {
        config.headers["Authorization"] = ""
    }
    // 在发送请求之前做些什么
    changeSpinning(true)
    return config;
}, function (error) {
    // 对请求错误做些什么
    changeSpinning(false)
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    changeSpinning(false)
    return response;

}, function (error) {
    // 对响应错误做点什么 
    const status = error.response.status
    switch (status) {
        case 404:
            message.error(error.message)
            break;
    }
    changeSpinning(false)
    return Promise.reject(error);
});
const request = (options: RequestParams): Promise<any> => {

    return new Promise((resolve, reject) => {

        if (options.method == 'GET' || options.method == 'DELETE') {
            instance.request({
                url: options.url,
                method: options.method,
                params: options.data
            }).then((response) => {
                if (response.data.code == 200) {
                    resolve(response.data);
                } else {
                    message.error(response.data.msg)
                    reject(response)
                }
            })
        }
        if (options.method == 'POST' || options.method == 'PUT') {
            instance.request({
                url: `${options.url}?${jsonToQueryString(options.data)}`,
                method: options.method,
                data: options.data,
            }).then((response) => {
                console.log()
                if (response.data.code == 200) {
                    resolve(response.data);

                } else {
                    message.error(response.data.msg)
                    reject(response)
                }
            })
        }
    })
}
export default request